//
//  MainViewController.m
//  quickBatchManager
//
//  Created by jack on 15/9/15.
//  Copyright (c) 2015年 jack. All rights reserved.
//

#import "MainViewController.h"
#import "AppDelegate.h"
#define leftViewWidthClose 165
#define leftViewWidthOpen 535

typedef enum
{
    collectionViewImage=1,//图片展示
    collectionViewList=2, //列表展示
    collectionViewTable=3, //表格展示
} CollectionViewType;

@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate,ChooseDelegate,ChangeDelegate,AAMenuBubblesDelegate,PMCalendarControllerDelegate,UIAlertViewDelegate>
@property (nonatomic, strong) PMCalendarController *pmCC;
@property (assign,nonatomic) CollectionViewType collectionType;
@property (nonatomic,strong) NSArray *images;
@end

@implementation MainViewController
{
    /** 左边view**/
    UIView *leftView;
    UIImageView *leftImageView;
    UIView *tabView;
    UITableView *orderTableView;        //开单
    UITableView *categoryTableView;     //分类
    UIButton *addBtn;
    UILabel *dateLabel;
    UIView *orderContentView;
    UIView *mOrderView;
    UITextField *mobileTextField;
    UITextField *remarkTextField;
    UILabel *orderInfoLabel;
    BOOL flag;
    NSMutableArray *categoryArray;      //分类数据
    AAMenuBubbles *payMenu;
    UILabel *payLabel;
    UIButton *danjuBtn;
    NSMutableArray *queryParams;
    UIButton *bianjiBtn;
    UIImageView *yzfImageView;
    UILabel *zfInfoLabel;
    
    
    /** 右边view**/
    UIView *rightView;
    UIView *btnView;
    UIButton *imageBtn;
    UIButton *tableBtn;
    UIButton *listBtn;
    UICollectionView *mCollectionView;
    UITableView *clientTableView;      //客户列
    BOOL isEditing;
    UILabel *totalLabel;
    
    
    /**滑出页面**/
    UITextField *clientNameTextView;
    NSMutableArray *productList;
    
    /**数据**/
    NSMutableArray *clientTagArray;
    NSMutableArray *mainProductArray;
    NSMutableArray *mainProductInfoArray;
    
    NSMutableArray *listProductInfoArray;
    
    /**当前编辑的订单号**/
    SaleOrderModel *saleOrder;
    ClientModel *client;
    BOOL isEditClientName;
    NSDate *nowDate;
    
    
    
    AppDelegate *appDelegate;
    int index;
}
@synthesize pmCC;
- (void)viewDidLoad {
    flag = NO;
    [super viewDidLoad];
    isEditClientName = NO;
    index = 0;
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self reloadProductData];
    [clientTableView reloadData];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    sessionControl = [[WSSessionController sharedController]init];
    
}

- (void)_accessoryDidDisconnect:(NSNotification *)notification{
    
    // [[self navigationController] popViewControllerAnimated:YES];
    
    if (sessionControl != nil) {
        sessionControl = nil;
    }
}


-(void)initData
{
    isEditing = false;
    categoryArray = [CategoryModel searchWithWhere:nil];
    _collectionType = collectionViewImage;
    
    productList = [NSMutableArray array];
    listProductInfoArray= [NSMutableArray array];
    queryParams = [NSMutableArray array];
    
    
    
}

//重新加载数据
-(void) reloadProductData
{

    if(queryParams.count>0)
    {
         NSMutableString *str = [NSMutableString string];
        for (int i=0; i<[queryParams count]; i++) {
            if(i==[queryParams count]-1)
            {
               [str appendString:[NSString stringWithFormat:@"categoryId=%d",[queryParams[i] integerValue]]];
            }else
            {
               [str appendString:[NSString stringWithFormat:@"categoryId=%d or ",[queryParams[i] integerValue]]];
            }
        }
        NSLog(@"data===%@",str);
         mainProductArray = [ProductModel searchWithWhere:[NSString stringWithFormat:@"isDel = 0 and (%@)",str] orderBy:nil offset:0 count:0];
    }else
    {
         mainProductArray = [ProductModel searchWithWhere:@{@"isDel":@"0"}];
    }
  
    [mCollectionView reloadData];
}

-(void)initUI
{
    
    
    /*********** left View *******************/
    leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, leftViewWidthClose, SCREEN_HEIGHT)];
    leftImageView = [[UIImageView alloc] initWithFrame:leftView.bounds];
    [leftImageView setImage:[UIImage imageNamed:@"beijingtu02"]];
    [leftView addSubview:leftImageView];
    
    tabView  = [[UIView alloc] initWithFrame:CGRectMake(leftView.frame.size.width - 40, 0, 40, SCREEN_HEIGHT)];
    UIImageView *tabImageView = [[UIImageView alloc] initWithFrame:tabView.bounds];
    [tabImageView setImage:[UIImage imageNamed:@"beijingtu02"]];
    [tabView addSubview:tabImageView];
    [leftView addSubview:tabView];
    
    UIButton *kaidanBtn = [[UIButton alloc] initWithFrame:CGRectMake(marginSize, 20, 110, 48)];
    [kaidanBtn setImage:[UIImage imageNamed:@"kaidan_1"] forState:UIControlStateNormal];
    [kaidanBtn setImage:[UIImage imageNamed:@"kaidan_2"] forState:UIControlStateSelected];
    [kaidanBtn setImage:[UIImage imageNamed:@"kaidan_2"] forState:UIControlStateHighlighted];
    [leftView addSubview:kaidanBtn];
    
    UIButton *daohuoBtn = [[UIButton alloc] initWithFrame:CGRectMake(marginSize, 80, 110, 48)];
    [daohuoBtn setImage:[UIImage imageNamed:@"daohuo_1"] forState:UIControlStateNormal];
    [daohuoBtn setImage:[UIImage imageNamed:@"daohuo_2"] forState:UIControlStateSelected];
    [daohuoBtn setImage:[UIImage imageNamed:@"daohuo_2"] forState:UIControlStateHighlighted];
    [leftView addSubview:daohuoBtn];
    
    UIButton *zhangmuBtn = [[UIButton alloc] initWithFrame:CGRectMake(marginSize, 145, 110, 48)];
    [zhangmuBtn setImage:[UIImage imageNamed:@"zhangmu_1"] forState:UIControlStateNormal];
    [zhangmuBtn setImage:[UIImage imageNamed:@"zhangmu_2"] forState:UIControlStateSelected];
    [zhangmuBtn setImage:[UIImage imageNamed:@"zhangmu_2"] forState:UIControlStateHighlighted];
    [leftView addSubview:zhangmuBtn];
    
    danjuBtn = [[UIButton alloc] initWithFrame:CGRectMake(marginSize, 210, 110, 48)];
    [danjuBtn setImage:[UIImage imageNamed:@"danju_1"] forState:UIControlStateNormal];
    [danjuBtn setImage:[UIImage imageNamed:@"danju_2"] forState:UIControlStateSelected];
    [danjuBtn setImage:[UIImage imageNamed:@"danju_2"] forState:UIControlStateHighlighted];
    [leftView addSubview:danjuBtn];
    
    bianjiBtn = [[UIButton alloc] initWithFrame:CGRectMake(marginSize, 275, 110, 48)];
    [bianjiBtn setImage:[UIImage imageNamed:@"bianji_1"] forState:UIControlStateNormal];
    [bianjiBtn setImage:[UIImage imageNamed:@"bianji_2"] forState:UIControlStateSelected];
    [bianjiBtn setImage:[UIImage imageNamed:@"bianji_2"] forState:UIControlStateHighlighted];
    [bianjiBtn setImage:[UIImage imageNamed:@"bianji_2"] forState:UIControlStateReserved];
    [leftView addSubview:bianjiBtn];
    
    
    UIButton *addFenleiBtn = [[UIButton alloc] initWithFrame:CGRectMake(marginSize, 380, 110, 48)];
    [addFenleiBtn setImage:[UIImage imageNamed:@"tianjiafenlei_1"] forState:UIControlStateNormal];
    [addFenleiBtn setImage:[UIImage imageNamed:@"tianjiafenlei_2"] forState:UIControlStateSelected];
    [addFenleiBtn setImage:[UIImage imageNamed:@"tianjiafenlei_2"] forState:UIControlStateHighlighted];
    [leftView addSubview:addFenleiBtn];
    
    UITextField *searchField = [[UITextField alloc] initWithFrame:CGRectMake(marginSize, 440, 110, 35)];
    CGRect frame = [searchField frame];
    frame.size.width = 30.0f;
    UIView *mleftview = [[UIView alloc] initWithFrame:frame];
    searchField.leftView = mleftview;
    searchField.leftViewMode = UITextFieldViewModeAlways;
    [searchField setBackground:[UIImage imageNamed:@"sousuo"]];
    searchField.keyboardType = UIKeyboardTypeNumberPad;
    [searchField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [leftView addSubview:searchField];
    
    UIImageView *sIcon = [[UIImageView alloc] initWithFrame:CGRectMake(marginSize+5, 448, 20, 20)];
    [sIcon setContentMode:UIViewContentModeScaleToFill];
    [sIcon setImage:[UIImage imageNamed:@"searchicon"]];
    [leftView addSubview:sIcon];
    
    
    
    
    categoryTableView  = [[UITableView alloc] initWithFrame:CGRectMake(marginSize, CGRectGetMaxY(searchField.frame)+marginSize, 110, SCREEN_HEIGHT - CGRectGetMaxY(searchField.frame) - marginSize)];
    [categoryTableView setBackgroundColor:[UIColor clearColor]];
    // categoryTableView.layer.borderWidth = 1;
    categoryTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    categoryTableView.delegate = self;
    categoryTableView.dataSource = self;
    [leftView addSubview:categoryTableView];
    [danjuBtn bk_whenTapped:^{
        index=2;
        if(appDelegate.opType==DianZhang)
        {
            TicketListViewController *tlvc=[[TicketListViewController alloc] init];
            BaseNavigationController *nav=[[BaseNavigationController alloc] initWithRootViewController:tlvc];
            [self.navigationController presentViewController:nav animated:YES completion:nil];
        }else
        {
            GesturePasswordController *gpc=[[GesturePasswordController alloc] init];
            gpc.modalPresentationStyle=UIModalPresentationFormSheet;
            gpc.delegate=self;
            [self presentViewController:gpc animated:YES completion:nil];
        }
       
    }];
    
    [zhangmuBtn bk_whenTapped:^{
        index=1;
        if(appDelegate.opType==DianZhang)
        {
            AccountListViewController *settingVc = [[AccountListViewController alloc] init];
            BaseSplitViewController  *settingsplitViewController = [[BaseSplitViewController alloc]init];
            [settingsplitViewController setValue:[NSNumber numberWithFloat:SCREEN_WIDTH/2] forKey:@"_masterColumnWidth"];
            //[settingsplitViewController setValue:[NSNumber numberWithFloat:SCREEN_HEIGHT] forKey:@"_masterColumnHeight"];
            [settingsplitViewController setPresentsWithGesture:YES];
            [settingsplitViewController setViewControllers:[NSArray arrayWithObjects:settingVc,nil, nil]];//横向时index:0左边导航展示，index:1为右边显示的view
            settingsplitViewController.view.backgroundColor = RGBCOLOR(88,34,8);
            
            [settingsplitViewController.view setBackgroundColor:BACKGROUND_COLOR];
            [self.navigationController presentViewController:settingsplitViewController animated:YES completion:nil];
        }else
        {
            GesturePasswordController *gpc=[[GesturePasswordController alloc] init];
            gpc.modalPresentationStyle=UIModalPresentationFormSheet;
            gpc.delegate=self;
            [self presentViewController:gpc animated:YES completion:nil];
        }
     
        
    }];
    
    
    [kaidanBtn bk_whenTapped:^{
        
        [UIView animateWithDuration:0.5 animations:^{
            if(!flag)
            {
                saleOrder=[AppService getNewSaleOrder];
                nowDate=[NSDate dateFromString:saleOrder.date andFormat:YYYYMMDDHHMMSS];
                [self leftViewOpen];
            }
        }];
        
        
    }];
    
    [bianjiBtn bk_whenTapped:^{
        index=3;
        if(appDelegate.opType==DianZhang || bianjiBtn.isSelected)
        {
            bianjiBtn.selected = !bianjiBtn.selected;
            isEditing  = bianjiBtn.selected;
            [clientTableView reloadData];
            [mCollectionView reloadData];
        }else
        {
            GesturePasswordController *gpc=[[GesturePasswordController alloc] init];
            gpc.modalPresentationStyle=UIModalPresentationFormSheet;
            gpc.delegate=self;
            [self presentViewController:gpc animated:YES completion:nil];
        }
      
    }];
    
    [daohuoBtn bk_whenTapped:^{
        index=0;
        if(appDelegate.opType==DianZhang)
        {
            PutInProductViewController *pipvc=[[PutInProductViewController alloc] init];
            [self.navigationController pushViewController:pipvc animated:YES];
        }else
        {
            GesturePasswordController *gpc=[[GesturePasswordController alloc] init];
            gpc.modalPresentationStyle=UIModalPresentationFormSheet;
            gpc.delegate=self;
            [self presentViewController:gpc animated:YES completion:nil];
        }
  
    }];
    
    [addFenleiBtn bk_whenTapped:^{
        AddCategoryViewController *vc=[[AddCategoryViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        vc.delegate = self;
        [self presentViewController:vc animated:YES completion:nil];
    }];
    
    /*********** right View *******************/
    rightView = [[UIView alloc] initWithFrame:CGRectMake(leftViewWidthClose, 0, SCREEN_WIDTH - 60 - leftView.frame.size.width, SCREEN_HEIGHT)];
    //[rightView setBackgroundColor:[UIColor colorWithRed:250/255.0 green:248/255.0 blue:241/255.0 alpha:1]];
    btnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, rightView.frame.size.width, 50)];
    [btnView setBackgroundColor:[UIColor colorWithRed:236/255.0 green:232/255.0 blue:226/255.0 alpha:1]];
    imageBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, btnView.frame.size.width/3, btnView.frame.size.height)];
    [imageBtn setBackgroundColor:[UIColor colorWithRed:205/255.0 green:171/255.0 blue:150/255.0 alpha:0.5]];
    [imageBtn setTitle:@"图片" forState:UIControlStateNormal];
    [imageBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [imageBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    imageBtn.selected = YES;
    
    
    UIImageView *rightImageView = [[UIImageView alloc] initWithFrame:rightView.bounds];
    [rightImageView setImage:[UIImage imageNamed:@"beijingtur"]];
    [rightView addSubview:rightImageView];
    
    tableBtn = [[UIButton alloc] initWithFrame:CGRectMake(btnView.frame.size.width/3, 0, btnView.frame.size.width/3, btnView.frame.size.height)];
    [tableBtn setTitle:@"表格" forState:UIControlStateNormal];
    [tableBtn setBackgroundColor:[UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:0.5]];
    [tableBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [tableBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    listBtn = [[UIButton alloc] initWithFrame:CGRectMake(btnView.frame.size.width/3 *2, 0, btnView.frame.size.width/3, btnView.frame.size.height)];
    [listBtn setTitle:@"列表" forState:UIControlStateNormal];
      [listBtn setBackgroundColor:[UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:0.5]];
    [listBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [listBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [btnView addSubview:imageBtn];
    [btnView addSubview:tableBtn];
    [btnView addSubview:listBtn];
    [rightView addSubview:btnView];
    
    
    totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, rightView.frame.size.height-40, rightView.frame.size.width, 40)];
    [totalLabel setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.7]];
    [totalLabel setTextColor:[UIColor whiteColor]];
    NSMutableArray *modelNumber = [ProductModel searchWithWhere:@"isDel = 0" orderBy:nil groupBy:@"modelNo" offset:0 count:0];
  //  saleOrder.orderPrice = [SaleOrderInfoModel sumWithWhere:@"productNumber*price" where:@{@"saleOrderId":[ToolUtils numberToStr:saleOrderId]}];
    double number = [ProductModel sumWithWhere:@"totalNumber" where:@"isDel = 0"];
    double money = [ProductModel sumWithWhere:@"totalNumber*salePrice" where:@"isDel = 0"];
    [totalLabel setText:[NSString stringWithFormat:@"    共有%d款式,共有%0.0f件,总金额%0.1f",[modelNumber count],number,money]];
    [rightView addSubview:totalLabel];
    
    [imageBtn bk_whenTapped:^{
        _collectionType = collectionViewImage;
        [imageBtn setBackgroundColor:[UIColor colorWithRed:205/255.0 green:171/255.0 blue:150/255.0 alpha:0.5]];
        [tableBtn setBackgroundColor:[UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:0.5]];
        [listBtn setBackgroundColor:[UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:0.5]];
        [rightView addSubview:[self setupCollectionView:_collectionType]];
        [imageBtn setSelected:YES];
        [tableBtn setSelected:NO];
        [listBtn setSelected:NO];
        
    }];
    
    [tableBtn bk_whenTapped:^{
        _collectionType = collectionViewTable;
        [tableBtn setBackgroundColor:[UIColor colorWithRed:205/255.0 green:171/255.0 blue:150/255.0 alpha:0.5]];
        [imageBtn setBackgroundColor:[UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:0.5]];
        [listBtn setBackgroundColor:[UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:0.5]];
        [rightView addSubview:[self setupCollectionView:_collectionType]];
        [imageBtn setSelected:NO];
        [tableBtn setSelected:YES];
        [listBtn setSelected:NO];
    }];
    
    [listBtn bk_whenTapped:^{
        _collectionType = collectionViewList;
        [listBtn setBackgroundColor:[UIColor colorWithRed:205/255.0 green:171/255.0 blue:150/255.0 alpha:0.5]];
        [imageBtn setBackgroundColor:[UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:0.5]];
        [tableBtn setBackgroundColor:[UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:0.5]];
        [rightView addSubview:[self setupCollectionView:_collectionType]];
        [imageBtn setSelected:NO];
        [tableBtn setSelected:NO];
        [listBtn setSelected:YES];
    }];
    
    
   
    
    
    
    /***** 添加Collectionview*****/
    [rightView addSubview:[self setupCollectionView:_collectionType]];
    
    /***** 添加客户tag*****/
    [leftView addSubview:[self setupClientTagView]];
    
    /***** 添加左右view*****/
    [self.view addSubview:leftView];
    [self.view addSubview:rightView];
}

/**
 *  展开
 */
-(void)leftViewOpen
{
    flag  = YES; 
    [leftView setFrame:CGRectMake(0, 0, leftViewWidthOpen, SCREEN_HEIGHT)];
    [rightView setFrame:CGRectMake(leftViewWidthOpen, 0, SCREEN_WIDTH - 60 - leftView.frame.size.width, SCREEN_HEIGHT)];
    [leftImageView setFrame:leftView.bounds];
    [tabView  setFrame:CGRectMake(leftView.frame.size.width - 40, 0, 40, SCREEN_HEIGHT)];
    [btnView setFrame:CGRectMake(0, 0, rightView.frame.size.width, 50)];
    [imageBtn setFrame:CGRectMake(0, 0, btnView.frame.size.width/3, btnView.frame.size.height)];
    [tableBtn setFrame:CGRectMake(btnView.frame.size.width/3, 0, btnView.frame.size.width/3, btnView.frame.size.height)];
    [listBtn setFrame:CGRectMake(btnView.frame.size.width/3 *2, 0, btnView.frame.size.width/3, btnView.frame.size.height)];
    [clientTableView setHidden:YES];
    
    if(mOrderView)
    {
        [mOrderView removeFromSuperview];
    }
    mOrderView = [self setupOrderView];
    [leftView addSubview:mOrderView];
    
    
    
    AFTER_MAIN(0.5, ^{
        if(mOrderView)
        {
            [mCollectionView setFrame:CGRectMake(5, CGRectGetMaxY(btnView.frame), btnView.frame.size.width-marginSize+5, rightView.frame.size.height - btnView.frame.size.height)];
            [mCollectionView reloadData];
        }
    });
    
}
/**
 *  关闭
 */
-(void)leftViewClose
{
    flag = NO;
    [leftView setFrame:CGRectMake(0, 0, leftViewWidthClose, SCREEN_HEIGHT)];
    [leftImageView setFrame:leftView.bounds];
    [rightView setFrame:CGRectMake(leftViewWidthClose, 0, SCREEN_WIDTH - 60 - leftView.frame.size.width, SCREEN_HEIGHT)];
    [tabView  setFrame:CGRectMake(leftView.frame.size.width - 40, 0, 40, SCREEN_HEIGHT)];
    [btnView setFrame:CGRectMake(0, 0, rightView.frame.size.width, 50)];
    [imageBtn setFrame:CGRectMake(0, 0, btnView.frame.size.width/3, btnView.frame.size.height)];
    [tableBtn setFrame:CGRectMake(btnView.frame.size.width/3, 0, btnView.frame.size.width/3, btnView.frame.size.height)];
    [listBtn setFrame:CGRectMake(btnView.frame.size.width/3 *2, 0, btnView.frame.size.width/3, btnView.frame.size.height)];
    [mCollectionView    setFrame:CGRectMake(0, CGRectGetMaxY(btnView.frame), btnView.frame.size.width-marginSize+5, rightView.frame.size.height - btnView.frame.size.height)];
    // [mCollectionView reloadData];
    AFTER_MAIN(0.5, ^{
        if(mOrderView)
        {
            [mOrderView removeFromSuperview];
            [clientTableView setHidden:NO];
        }
    });
    
}


-(UITableView *)setupClientTagView
{
    clientTableView = [[UITableView alloc] initWithFrame:CGRectMake(leftView.frame.size.width - 47
                                                                    
                                                                    , marginSize, 45, SCREEN_HEIGHT)];
    clientTableView.backgroundColor = [UIColor clearColor];
    clientTableView.dataSource = self;
    clientTableView.delegate = self;
    [clientTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    return clientTableView;
}

/**
 *  根据类型装载展示模式
 *
 */
-(UICollectionView *)setupCollectionView:(CollectionViewType) type
{
    if(mCollectionView!=nil)
    {
        [mCollectionView removeFromSuperview];
        mCollectionView = nil;
    }
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    if(type==collectionViewImage)
    {
        [flowLayout setItemSize:CGSizeMake(140, 190)];//设置cell的尺寸
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];//设置其布局方向
        flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);//设置其边界
        flowLayout.footerReferenceSize = CGSizeMake(300, 30);
        flowLayout.minimumLineSpacing = 10;
        flowLayout.minimumInteritemSpacing = 10;
    }else if (type==collectionViewList)
    {
        [flowLayout setItemSize:CGSizeMake(250, 80)];//设置cell的尺寸
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];//设置其布局方向
        flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);//设置其边界
        flowLayout.footerReferenceSize = CGSizeMake(300, 30);
        flowLayout.minimumLineSpacing = 10;
        flowLayout.minimumInteritemSpacing = 10;
    }else
    {
        //  [flowLayout setItemSize:CGSizeMake(250, 0)];//设置cell的尺寸
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];//设置其布局方向
        flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);//设置其边界
        flowLayout.footerReferenceSize = CGSizeMake(300, 10);
        flowLayout.minimumLineSpacing = 10;
        flowLayout.minimumInteritemSpacing = 10;
    }
    
    //其布局很有意思，当你的cell设置大小后，一行多少个cell，由cell的宽度决定
    mCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(btnView.frame), btnView.frame.size.width-marginSize+5, rightView.frame.size.height - btnView.frame.size.height)collectionViewLayout:flowLayout];
    if(type==collectionViewImage)
    {
        [mCollectionView registerClass:[ImageCell class] forCellWithReuseIdentifier:@"ImageCell"];
        
    }else if (type==collectionViewList)
    {
        [mCollectionView registerClass:[ListCell class] forCellWithReuseIdentifier:@"ListCell"];
    }else
    {
        [listProductInfoArray removeAllObjects];
        
        
        for (ProductModel *data in mainProductArray) {
            NSMutableArray *p1=[[NSMutableArray alloc] init];
            TableModel *model=[[TableModel alloc] init];
            model.tableList=p1;
            model.modelTitle=data.modelNo;
            model.totalTitle=[NSString stringWithFormat:@"￥ %0.1f元 存:%0.0f件",data.totalNumber*data.salePrice,data.totalNumber];
            
            [listProductInfoArray addObject:model];
            NSArray *sizeList=[ProductInfoModel searchWithWhere:@{@"productId":[ToolUtils numberToStr:data.productId]} orderBy:nil groupBy:@"sizeName" offset:0 count:0];
            NSArray *colorList=[ProductInfoModel searchWithWhere:@{@"productId":[ToolUtils numberToStr:data.productId]} orderBy:nil groupBy:@"colorName" offset:0 count:0];
            
            for (int i=0; i<=colorList.count; i++) {
                NSMutableArray *p2=[[NSMutableArray alloc] init];
                [p1 addObject:p2];
                for (int j=0; j<=sizeList.count; j++)
                {
                    if(i==0 && j==0)
                    {
                        [p2 addObject:@"颜色"];
                    }
                    else if(i==0)
                    {
                        ProductInfoModel *ap=[sizeList objectAtIndex:j-1];
                        [p2 addObject:ap.sizeName];
                    }
                    else if(j==0)
                    {
                        ProductInfoModel *ap=[colorList objectAtIndex:i-1];
                        [p2 addObject:ap.colorName];
                    }
                    else  {
                        ProductInfoModel *sp=[sizeList objectAtIndex:j-1];
                        ProductInfoModel *cp=[colorList objectAtIndex:i-1];
                        [p2 addObject:[ToolUtils numberToStr:[ProductInfoModel sumWithWhere:@"productNumber" where:@{@"productId":[ToolUtils numberToStr:data.productId],@"sizeName":sp.sizeName,@"colorName":cp.colorName}]]];
                    }
                }
            }
            
            
            
        }
        
        [mCollectionView registerClass:[ProductTableCell class] forCellWithReuseIdentifier:@"ProductTableCell"];
    }
    mCollectionView.dataSource = self;
    mCollectionView.delegate = self;
    [mCollectionView setBackgroundColor:[UIColor clearColor]];
    //mCollectionView.layer.borderWidth = 1;
    return mCollectionView;
    
}

/**
 *  装载左侧滑出的订单页
 *
 */
-(UIView *)setupOrderView
{
    isEditClientName = NO;
    UIView *orderView = [[UIView alloc] initWithFrame:CGRectMake(leftViewWidthClose - marginSize*2, 0, leftViewWidthOpen - leftViewWidthClose, SCREEN_HEIGHT)];
    //    [orderView setBackgroundColor:[UIColor grayColor]];
    UIView *orderTopView  = [[UIView alloc] initWithFrame:CGRectMake(0, marginSize, orderView.frame.size.width, 60)];
    //   [orderTopView setBackgroundColor:[UIColor redColor]];
    UIButton *clientBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, marginSize, 50, 35)];
    [clientBtn setImage:[UIImage imageNamed:@"kehu_1"] forState:UIControlStateNormal];
    clientNameTextView = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(clientBtn.frame)+marginSize, marginSize, 100, 40)];
    [clientNameTextView setBackgroundColor:[UIColor clearColor]];
    [clientNameTextView setPlaceholder:@"请输入客户名称"];
    [clientNameTextView setFont:[UIFont systemFontOfSize:13]];
    clientNameTextView.delegate = self;
    [orderTopView addSubview:clientBtn];
    [orderTopView addSubview:clientNameTextView];
    
    
    
    UIButton *detailsBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(clientNameTextView.frame)+100, marginSize, 50, 35)];
    [detailsBtn setImage:[UIImage imageNamed:@"xiangqing_1"] forState:UIControlStateNormal];
    //[detailsBtn setImage:[UIImage imageNamed:@"btnxiangqing_s"] forState:UIControlStateHighlighted];
    [orderTopView addSubview:detailsBtn];
    
    [detailsBtn bk_whenTapped:^{
        OrderDetailsViewController *detailsVC = [[OrderDetailsViewController alloc] init];
        detailsVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        detailsVC.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        detailsVC.saleOrder = saleOrder;
        [self presentViewController:detailsVC animated:YES completion:nil];
    }];
    
    
    UIButton *guanbiBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(detailsBtn.frame)+marginSize, marginSize, 50, 35)];
    [guanbiBtn setImage:[UIImage imageNamed:@"guanbi_1"] forState:UIControlStateNormal];
   // [guanbiBtn setImage:[UIImage imageNamed:@"btnguanbi_s"] forState:UIControlStateHighlighted];
    [orderTopView addSubview:guanbiBtn];
    
    [guanbiBtn bk_whenTapped:^{
        [productList removeAllObjects];
        [UIView animateWithDuration:0.5 animations:^{
            [self leftViewClose];
        }];
        [clientTableView reloadData];
        [mCollectionView reloadData];
        
        
    }];
    
    [clientBtn bk_whenTapped:^{
        AddClientViewController *vc=[[AddClientViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        vc.delegate = self;
        [self presentViewController:vc animated:YES completion:nil];
    }];
    
    
    [orderView addSubview:orderTopView];
    
    orderContentView = [[UIView alloc] initWithFrame
                        :CGRectMake(0, CGRectGetMaxY(orderTopView.frame), orderView.frame.size.width, SCREEN_HEIGHT - orderTopView.frame.size.height - 60)];
    UIImageView *bgView = [[UIImageView alloc] initWithFrame:orderContentView.bounds];
    [bgView setImage:[UIImage imageNamed:@"bg_kaidanneirong"]];
    [orderContentView addSubview:bgView];
    orderContentView.layer.cornerRadius = 5.0f;
    orderContentView.layer.masksToBounds = YES;
    [orderView addSubview:orderContentView];
    
    UIImageView *dateImageView = [[UIImageView alloc] initWithFrame:CGRectMake(marginSize, marginSize*3, 15, 15)];
    [dateImageView setImage:[UIImage imageNamed:@"edi2"]];
    [orderContentView addSubview:dateImageView];
    
    dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(dateImageView.frame)+marginSize, dateImageView.frame.origin.y, 150, 25)];
    //  [dateLabel setText:[DateUtils dateToStringByFormat:[NSDate date]  format:YYYYMMDD]];
    [dateLabel setTextColor:[UIColor blackColor]];
    [orderContentView addSubview:dateLabel];
    
    UIButton *payBtn = [[UIButton alloc] initWithFrame:CGRectMake(orderContentView.frame.size.width - 100 - marginSize, marginSize+10, 100, 40)];
    [payBtn setImage:[UIImage imageNamed:@"hongdi"] forState:UIControlStateNormal];
    [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    payLabel = [[UILabel alloc] initWithFrame:payBtn.bounds];
    [payLabel setText:@"未付款"];
    [payLabel setTextAlignment:NSTextAlignmentCenter];
    [payLabel setTextColor:[UIColor whiteColor]];
    [payLabel setFont:[UIFont systemFontOfSize:13]];
    [payBtn addSubview:payLabel];
    [orderContentView addSubview:payBtn];
    
    [payBtn bk_whenTapped:^{
        if(payMenu) {
            payMenu = nil;
        }
        if(saleOrder.isPay)
        {
            yzfImageView.hidden = YES;
            saleOrder.isPay=  NO;
            [saleOrder updateToDB];
            [self reloadOrderListData];
           
        }else
        {
            NSArray *datas = [[NSString stringWithFormat:@"%@%@",[CoreArchive strForKey:NSDEFAULT_ST_PAYMENT],[CoreArchive boolForKey:NSDEFAULT_ST_PAYMENT_DS ]?@"|代收":@""] componentsSeparatedByString:@"|"];
            payMenu = [[AAMenuBubbles alloc] initWithPoint:CGPointMake(450, 100) radius:90 andBubbles:datas inView:self.view];
            payMenu.bubbleRadius = 30;
            payMenu.delegate=self;
            [payMenu show];
        }
      
    }];
    
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(marginSize, CGRectGetMaxY(dateLabel.frame)+marginSize, orderContentView.frame.size.width-marginSize*2, 40)];
    [titleView setBackgroundColor:[UIColor colorWithRed:254/255.0 green:190/255.0 blue:134/255.0 alpha:1]];
    
    UILabel *idLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleView.frame.size.width/4, 40)];
    [idLabel setTextAlignment:NSTextAlignmentCenter];
    [idLabel setText:@"款号"];
    
    UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleView.frame.size.width/4, 0, titleView.frame.size.width/4, 40)];
    [numberLabel setTextAlignment:NSTextAlignmentCenter];
    [numberLabel setText:@"数量"];
    
    UILabel *pricesLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleView.frame.size.width/2, 0, titleView.frame.size.width/4, 40)];
    [pricesLabel setTextAlignment:NSTextAlignmentCenter];
    [pricesLabel setText:@"单价"];
    
    UILabel *moneyLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleView.frame.size.width -titleView.frame.size.width/4 , 0, titleView.frame.size.width/4, 40)];
    [moneyLabel setTextAlignment:NSTextAlignmentCenter];
    [moneyLabel setText:@"金额"];
    
    
    [titleView addSubview:idLabel];
    [titleView addSubview:numberLabel];
    [titleView addSubview:pricesLabel];
    [titleView addSubview:moneyLabel];
    [orderContentView addSubview:titleView];
    
    
    orderTableView = [[UITableView alloc] initWithFrame:CGRectMake(marginSize, CGRectGetMaxY(titleView.frame), titleView.frame.size.width, 0)];
    [orderTableView setBackgroundColor:[UIColor clearColor]];
    orderTableView.dataSource = self;
    orderTableView.delegate = self;
    [orderContentView addSubview:orderTableView];
    
    
    addBtn = [[UIButton alloc] initWithFrame:CGRectMake(orderContentView.frame.size.width/2-50
                                                        , CGRectGetMaxY(orderTableView.frame)+marginSize, 100, 40)];
    [addBtn setImage:[UIImage imageNamed:@"landi"] forState:UIControlStateNormal];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UILabel *addLabel = [[UILabel alloc] initWithFrame:addBtn.bounds];
    [addLabel setText:@"添加订单"];
    [addLabel setTextAlignment:NSTextAlignmentCenter];
    [addLabel setTextColor:[UIColor whiteColor]];
    [addLabel setFont:[UIFont systemFontOfSize:14]];
    [addBtn addSubview:addLabel];
    [orderContentView addSubview:addBtn];
    
    [addBtn bk_whenTapped:^{
        AddOrderViewController *addOrderVC = [[AddOrderViewController alloc] init];
        addOrderVC.delegate = self;
        addOrderVC.saleOrder = saleOrder;
        [self.navigationController pushViewController:addOrderVC animated:YES];
    }];
    
    
    
    yzfImageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, orderContentView.frame.size.height - 125, 80, 80)];
    [yzfImageView setContentMode:UIViewContentModeCenter];
    yzfImageView.hidden = YES;
    [yzfImageView setImage:[UIImage imageNamed:@"yzf"]];
    [orderContentView addSubview:yzfImageView];
    
    
    zfInfoLabel=  [[UILabel alloc] initWithFrame:CGRectMake(marginSize,orderContentView.frame.size.height - 150, orderContentView.frame.size.width-marginSize*2, 40)];
    [zfInfoLabel setTextAlignment:NSTextAlignmentCenter];
    [zfInfoLabel setBackgroundColor:[UIColor colorWithRed:175/255.0 green:180/255.0 blue:219/255.0 alpha:0.7]];
    zfInfoLabel.hidden = YES;
    [orderContentView addSubview:zfInfoLabel];
    
    /****** 底部备注 ******/
    UIImageView *editImageView = [[UIImageView alloc] initWithFrame:CGRectMake(marginSize, orderContentView.frame.size.height - 85, 15, 15)];
    [editImageView setImage:[UIImage imageNamed:@"edi2"]];
    [orderContentView addSubview:editImageView];
    
    UILabel *remarkLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(editImageView.frame)+5, orderContentView.frame.size.height - 90, 40, 30)];
    [remarkLabel setText:@"备注:"];
    [remarkLabel setFont:[UIFont systemFontOfSize:14]];
    [orderContentView addSubview:remarkLabel];
    
    remarkTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(remarkLabel.frame)+5,orderContentView.frame.size.height - 90, 200, 30)];
    remarkTextField.delegate = self;
    [orderContentView addSubview:remarkTextField];
    
    orderInfoLabel = [[UILabel alloc] initWithFrame:CGRectMake(marginSize, CGRectGetMaxY(editImageView.frame)+5, orderContentView.frame.size.width, 30)];
    // [orderInfoLabel setText:[NSString stringWithFormat:@"共%d款 出%d件 退%d件    总额:%d元",8,148,0,7780]];
    [orderInfoLabel setFont:[UIFont systemFontOfSize:14]];
    [orderContentView addSubview:orderInfoLabel];
    
    
    UIImageView *editImageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(marginSize,CGRectGetMaxY(orderInfoLabel.frame)+5, 15, 15)];
    [editImageView2 setImage:[UIImage imageNamed:@"edi2"]];
    [orderContentView addSubview:editImageView2];
    
    UILabel *mobileLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(editImageView.frame)+5, CGRectGetMaxY(orderInfoLabel.frame), 40, 30)];
    [mobileLabel setText:@"电话:"];
    [mobileLabel setFont:[UIFont systemFontOfSize:14]];
    [orderContentView addSubview:mobileLabel];
    
    mobileTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(mobileLabel.frame)+5, CGRectGetMaxY(orderInfoLabel.frame), 200, 30)];
    mobileTextField.delegate = self;
    [orderContentView addSubview:mobileTextField];
    
    editImageView.userInteractionEnabled = YES;
    editImageView2.userInteractionEnabled = YES;
    remarkLabel.userInteractionEnabled = YES;
    mobileLabel.userInteractionEnabled = YES;
    
    [editImageView bk_whenTapped:^{
        [remarkTextField becomeFirstResponder];
    }];
    
    [remarkLabel bk_whenTapped:^{
        [remarkTextField becomeFirstResponder];
    }];
    
    [editImageView2 bk_whenTapped:^{
        [mobileTextField becomeFirstResponder];
    }];
    
    [mobileLabel bk_whenTapped:^{
        [mobileTextField becomeFirstResponder];
    }];
    
    
    /**** 日历控件****/
    dateLabel.userInteractionEnabled = YES;
    dateLabel.text = [DateUtils dateToStringByFormat:[NSDate date] format:YYYYMMDD];
    [dateLabel bk_whenTapped:^{
        self.pmCC = [[PMCalendarController alloc] initWithThemeName:@"default"];
        self.pmCC.delegate = self;
        self.pmCC.mondayFirstDayOfWeek = NO;
        if ([self.pmCC isCalendarVisible])
        {
            [self.pmCC dismissCalendarAnimated:NO];
        }
        
        [self.pmCC presentCalendarFromView:dateLabel
                  permittedArrowDirections:PMCalendarArrowDirectionAny
                                 isPopover:YES
                                  animated:YES];
      self.pmCC.period = [PMPeriod oneDayPeriodWithDate:[NSDate date]];
    }];
    
    UIView *orderBootom = [[UIView alloc] initWithFrame:CGRectMake(0,  orderView.frame.size.height - 50, orderView.frame.size.width, 50)];
    /** 特殊操作，打印**/
    UIButton *teshuOpBtn = [[UIButton alloc] initWithFrame:CGRectMake(marginSize, 5, 80, 35)];
    [teshuOpBtn setImage:[UIImage imageNamed:@"teshucaozuo_1"] forState:UIControlStateNormal];
   // [teshuOpBtn setImage:[UIImage imageNamed:@"btnteshucaozuo_s"] forState:UIControlStateHighlighted];
    [orderBootom addSubview:teshuOpBtn];
    
    UIButton *printBtn = [[UIButton alloc] initWithFrame:CGRectMake(orderContentView.frame.size.width - 60, 5, 50, 35)];
    [printBtn setImage:[UIImage imageNamed:@"dayin_1"] forState:UIControlStateNormal];
    //[printBtn setImage:[UIImage imageNamed:@"btndayin_s"] forState:UIControlStateHighlighted];
    [orderBootom addSubview:printBtn];
    
    [printBtn bk_whenTapped:^{
        NSLog(@"printBtn");
        if(saleOrder)
            [PrintUtil printOrder:saleOrder andControl:sessionControl];
        
    }];
    [teshuOpBtn bk_whenTapped:^{
        NSLog(@"teshuOpBtnteshuOpBtn");
        TsczViewController *vc=[[TsczViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
         vc.delegate=self;
        vc.type = TsczOrder;
        vc.orderNo = saleOrder.saleOrderNo;
        [self presentViewController:vc animated:YES completion:nil];
    }];
    [orderView addSubview:orderBootom];
    
    return orderView;
}

#pragma mark --tableView datasource delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([tableView isEqual:orderTableView])
    {
        
        if(productList!=nil && [productList count]>0)
        {
            int m = [productList count]>9?9:[productList count];
            [tableView setFrame:CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, m*42)];
            [addBtn setFrame:CGRectMake(orderContentView.frame.size.width/2-50, CGRectGetMaxY(tableView.frame)+marginSize, 100, 40)];
            return [productList count];
        }
        else
        {
            return 0;
        }
        
        
        
        
    }else if ([tableView isEqual:clientTableView])
    {
        clientTagArray = [SaleOrderModel searchWithWhere:@"totalNumber!=0 and isArchive=0 and isDel=0"];
        if(clientTagArray!=nil)
        {
            return [clientTagArray count];
        }
        return 0;
    }else if ([tableView isEqual:categoryTableView])
    {
        if(categoryArray!=nil)
            return [categoryArray count]+1;
        else
            return 1;
    }else
    {
        return 0;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([tableView isEqual:orderTableView])
    {
        NSString *reuseIdetify = @"KaidanCell";
        KaidanCell  *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
        if(!cell){
            
            
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"KaidanCell" owner:self options:nil];
            for(id oneObject in nib){
                if([oneObject isKindOfClass:[KaidanCell class]]){
                    cell = (KaidanCell *) oneObject;
                }
            }
        }
        cell.backgroundColor = [UIColor clearColor];
        SaleOrderInfoModel *model = [productList objectAtIndex:indexPath.row];
        cell.productNumberLabel.text = model.product.modelNo;
        
     //   double total=[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"productId":[NSString stringWithFormat:@"%d",model.productId],@"saleOrderId":[ToolUtils numberToStr:model.saleOrderId]}];
        
        double total=[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"productId":[NSString stringWithFormat:@"%ld",(long)model.productId],@"saleOrderInfoId":[ToolUtils numberToStr:model.saleOrderInfoId]}];
        
        cell.numberLabel.text = [NSString stringWithFormat:@"%0.0f",total];
        cell.pricesLabel.text = [NSString stringWithFormat:@"%0.0f",model.price];
        cell.totalPricesLabel.text =  [NSString stringWithFormat:@"%0.0f",model.price * total];
         NSMutableArray *rightUtilityButtons = [NSMutableArray new];
        [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f] title:@"删除"];
        [cell setRightUtilityButtons:rightUtilityButtons];
        cell.delegate = self;
        cell.tag = indexPath.row;
        return cell;
    }else if ([tableView isEqual:clientTableView])
    {
        NSString *reuseIdetify = @"TagCell";
        TagCell  *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
        if(!cell){
            
            
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"TagCell" owner:self options:nil];
            for(id oneObject in nib){
                if([oneObject isKindOfClass:[TagCell class]]){
                    cell = (TagCell *) oneObject;
                }
            }
            
        }
        SaleOrderModel *model = [clientTagArray objectAtIndex:indexPath.row];
        if(isEditing)
        {
            cell.delImageView.hidden = NO;
        }else
        {
            cell.delImageView.hidden = YES;
        }
      //  cell.tagBg.image=[UIImage imageNamed:[NSString stringWithFormat:@"tag%d",indexPath.row%3]];
        cell.tagBg.image = [UIImage imageNamed:@"biaoqian"];
        [cell setData:model];
        
        NSString *titleTag =  model.client.clientName;
        if(![titleTag isValid])
        {
            titleTag = model.clientName;
            
        }
        if(![model.clientName isValid])
        {
            titleTag = [NSString stringWithFormat:@"订单%d",indexPath.row];
        }
        
        
        [cell.delImageView bk_whenTapped:^{
            NSLog(@"删除客户");
            model.isDel = YES;
            [model updateToDB];
            [clientTableView reloadData];
        }];
       
        
        cell.countLabel.text=[ToolUtils numberToStr:model.totalNumber];
        cell.tagLabel.text = titleTag;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        cell.mSuperView = self.view;
        cell.goodView = danjuBtn;
        cell.delegate = self;
        
        if(model.isPay)
        {
            cell.countLabel.textColor = [UIColor whiteColor];
            cell.tagLabel.textColor = [UIColor whiteColor];
        }else
        {
            cell.countLabel.textColor = [UIColor blackColor];
            cell.tagLabel.textColor = [UIColor blackColor];
        }
        
        return cell;
    }else if ([tableView isEqual:categoryTableView])
    {
        NSString *reuseIdetify = @"CategoryCell";
        CategoryCell  *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
        if(!cell){
            
            
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"CategoryCell" owner:self options:nil];
            for(id oneObject in nib){
                if([oneObject isKindOfClass:[CategoryCell class]]){
                    cell = (CategoryCell *) oneObject;
                }
            }
            
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        if(categoryArray && indexPath.row < (categoryArray.count))
        {
            CategoryModel *model = [categoryArray objectAtIndex:indexPath.row];
            cell.categoryBtn.tag=indexPath.row;
            [cell.categoryBtn setTitle:model.categoryName forState:UIControlStateNormal];
            
            UILongPressGestureRecognizer *categoryLongpressGesutre=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleCategoryLongpressGesture:)];
            
            //长按时间为1秒
            categoryLongpressGesutre.minimumPressDuration=0.8;
            categoryLongpressGesutre.numberOfTouchesRequired = 1;
            [cell.categoryBtn addGestureRecognizer:categoryLongpressGesutre];
            [cell.categoryBtn bk_whenTapped:^{
                cell.categoryBtn.highlighted = !cell.categoryBtn.highlighted;
                
                if(cell.categoryBtn.highlighted)
                {
                    [queryParams addObject:[NSString stringWithFormat:@"%ld",(long)model.categoryId]];
                }else
                {
                    for (int i=0; i<[queryParams count]; i++) {
                        NSString *str1 = queryParams[i];
                        NSString *str2 = [NSString stringWithFormat:@"%ld",(long)model.categoryId];
                        if([str1 isEqualToString:str2])
                        {
                            [queryParams removeObjectAtIndex:i];
                        }
                    }
                }
                
                [self reloadProductData];
            }];

        }else
        {
            //回收仓
             [cell.categoryBtn setTitle:@"回收仓" forState:UIControlStateNormal];
            
            
            [cell.categoryBtn bk_whenTapped:^{
                cell.categoryBtn.highlighted = !cell.categoryBtn.highlighted;
                if(cell.categoryBtn.highlighted)
                {
                    mainProductArray = [ProductModel searchWithWhere:[NSString stringWithFormat:@"isDel = 1"] orderBy:nil offset:0 count:0];
                }else
                {
                    [self reloadProductData];
                }
                
                [mCollectionView reloadData];
                
               
            }];

        }
        
        return cell;
    }else
    {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([tableView isEqual:orderTableView])
    {
        return 40;
    }else if ([tableView isEqual:clientTableView])
    {
        return 140;
    }else if([tableView isEqual:categoryTableView])
    {
        return 40;
    }else
    {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:clientTableView])
    {
        [UIView animateWithDuration:0.5 animations:^{
            if(!flag)
            {
                [self leftViewOpen];
                saleOrder = [clientTagArray objectAtIndex:indexPath.row];
                
                nowDate=[NSDate dateFromString:saleOrder.date andFormat:YYYYMMDDHHMMSS];
                
                mobileTextField.text = saleOrder.mobile;
                remarkTextField.text = saleOrder.remark;
                dateLabel.text = [saleOrder.date substringToIndex:10];
                clientNameTextView.text = saleOrder.client.clientName;
                if(![saleOrder.client.clientName isValid])
                {
                    clientNameTextView.text = saleOrder.clientName;
                }
                
                if(saleOrder.isPay)
                {
                    yzfImageView.hidden = NO;
                }else
                {
                    yzfImageView.hidden = YES;
                }
                
                
                [self reloadOrderListData];
            }
        } completion:^(BOOL finished) {
            
        }];
    }
    if ([tableView isEqual:orderTableView])
    {
        
        SaleOrderInfoModel *model = [productList objectAtIndex:indexPath.row];
        
        AddOrderViewController *addOrderVC = [[AddOrderViewController alloc] init];
        addOrderVC.isEdit = YES;
        addOrderVC.delegate = self;
        addOrderVC.modelNo = model.product.modelNo;
        addOrderVC.saleOrder= model;
        [self.navigationController pushViewController:addOrderVC animated:YES];
    }
    
    
}



#pragma mark --collectionView datasource delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(mainProductArray!=nil)
        return [mainProductArray count];
    return 0;
}


// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *reuseIdetify;
    ProductModel *model = [mainProductArray objectAtIndex:indexPath.row];
    if(_collectionType==collectionViewImage)
    {
        reuseIdetify = @"ImageCell";
        ImageCell  *imageCell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdetify forIndexPath:indexPath];
        imageCell.mSuperView = self.view;
        if(isEditing)
        {
            imageCell.editView.hidden = NO;
        }else
        {
            imageCell.editView.hidden = YES;
        }
        imageCell.parentVC=self;
        imageCell.delegate = self;
        imageCell.productNumberLabel.text = [NSString stringWithFormat:@"       %@",model.modelNo];
        imageCell.priceLabel.text = [NSString stringWithFormat:@"￥ %0.1f",model.salePrice];
        if([model.photo isValid])
        {
            NSString *imagePath = [ToolUtils getImageLocalPath:model.photo];
            [imageCell.productImageView setImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]]];
        }else
        {
            [imageCell.productImageView setImage:[UIImage imageNamed:@"nopic"]];
            
        }
        imageCell.isDrag = flag;
        imageCell.goodView = mOrderView;
        [imageCell setData:model];
        
        
        return imageCell;
    }else if (_collectionType == collectionViewList)
    {
        reuseIdetify = @"ListCell";
        ListCell  *listCell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdetify forIndexPath:indexPath];
        if(isEditing)
        {
            listCell.editView.hidden = NO;
        }else
        {
            listCell.editView.hidden = YES;
        }
        listCell.parentVC = self;
        listCell.productNumberLabel.text = model.modelNo;
        listCell.productInfoLabel.text = [NSString stringWithFormat:@"￥ %0.1f 合计:%0.0f件",model.salePrice,model.totalNumber];
        
        return listCell;
    }else if (_collectionType == collectionViewTable)
    {
        reuseIdetify = @"ProductTableCell";
        ProductTableCell *tableCell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdetify forIndexPath:indexPath];
        //        if(isEditing)
        //        {
        //            tableCell.editView.hidden = NO;
        //        }else
        //        {
        //            tableCell.editView.hidden = YES;
        //        }
        //
        
        [tableCell setData:[listProductInfoArray objectAtIndex:indexPath.row]];
        
        return tableCell;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(_collectionType==collectionViewImage)
    {
        if(mCollectionView.frame.size.width<500)
            return CGSizeMake(120, 150);
        else return CGSizeMake(140, 190);
    }else if (_collectionType == collectionViewList)
    {
        if(mCollectionView.frame.size.width>500)
            return CGSizeMake(250, 80);
        else  return CGSizeMake(350, 80);
    }else
    {
        TableModel *model=[listProductInfoArray objectAtIndex:indexPath.row];
        if(mCollectionView.frame.size.width<500)
        {
            return CGSizeMake(350, (model.tableList.count+2)*35);
        }
        else
            return CGSizeMake(250, (model.tableList.count+2)*35);
        
    }
    
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self localImageShow:indexPath.row];
    
}

#pragma mark PMCalendarControllerDelegate methods

- (void)calendarController:(PMCalendarController *)calendarController didChangePeriod:(PMPeriod *)newPeriod
{
    nowDate=newPeriod.startDate;
    dateLabel.text = [NSString stringWithFormat:@"%@"
                      , [newPeriod.startDate dateStringWithFormat:@"yyyy-MM-dd"]];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 9_0)
{
    if(buttonIndex==0)
    {
        //取消
        isEditClientName = NO;
        [clientNameTextView resignFirstResponder];
    }else
    {
        client.clientId = 0;
        isEditClientName = YES;
        [clientNameTextView becomeFirstResponder];
        
    }
}


#pragma mark--实现一些自定义回掉方法。。。。

-(void)tagDragToGoodView:(id)sender andSaleOrderModel:(SaleOrderModel *)saleOrderModel
{
    if(saleOrderModel.isPay)
    {
        saleOrderModel.isArchive  =YES;
        [saleOrderModel updateToDB];
        [clientTableView reloadData];
    }else
    {
        [self showAlert:@"此订单未付款不能收到单据"];
    }
}

-(void)imageDragToGoodView:(id)sender addProductModel:(ProductModel *)addProductModel
{
    if(addProductModel!=nil && [addProductModel isKindOfClass:[ProductModel class]])
    {
        AddOrderViewController *addOrderVC = [[AddOrderViewController alloc] init];
        addOrderVC.delegate = self;
        addOrderVC.saleOrder = saleOrder;
        addOrderVC.modelNo = addProductModel.modelNo;
        [self.navigationController pushViewController:addOrderVC animated:YES];
    }
}

#pragma mark--selectDelegate
-(void)didSelectData:(ChooseType)type andData:(id)data
{
    client=(ClientModel*)data;
    clientNameTextView.text = client.clientName;
    saleOrder= [AppService getSaleOrderByNo:saleOrder.saleOrderNo];
    saleOrder.clientId = client.clientId;
    saleOrder.remark = remarkTextField.text;
    saleOrder.date = [nowDate dateStringWithFormat:YYYYMMDDHHMMSS];
    saleOrder.mobile = mobileTextField.text;
    saleOrder.clientName = clientNameTextView.text;
    [saleOrder updateToDB];
}


#pragma mark--changeDelegate

-(void)didChange:(ChangeType)type andData:(id)data
{
    
    if(type==ChangeTypeOrder)
    {
        saleOrder=[AppService getSaleOrderByNo:saleOrder.saleOrderNo];
        [self reloadOrderListData];
        
    }
    else if(type==ChangeTypeCategory)
    {
        categoryArray = [CategoryModel searchWithWhere:nil];
        [categoryTableView reloadData];
    }
    
}


-(void) reloadOrderListData
{
    productList = [SaleOrderInfoModel searchWithWhere:@{@"saleOrderId":[ToolUtils numberToStr:saleOrder.saleOrderId]} orderBy:nil groupBy:@"saleOrderInfoId" offset:0 count:0];
    
    saleOrder= [AppService getSaleOrderByNo:saleOrder.saleOrderNo];
    [orderInfoLabel setText:[NSString stringWithFormat:@"共%d款 出%0.0f件 退%0.0f件    总额:%0.1f元",productList.count,[SaleOrderInfoModel sumWithWhere:@"productNumber" where:[NSString stringWithFormat:@"saleOrderId=%d and productNumber>0",saleOrder.saleOrderId]],[SaleOrderInfoModel sumWithWhere:@"productNumber" where:[NSString stringWithFormat:@"saleOrderId=%d and productNumber<0",saleOrder.saleOrderId]],saleOrder.orderPrice]];
    if([saleOrder.payType isValid] && saleOrder.isPay)
    {
        NSArray *datas = [[NSString stringWithFormat:@"%@%@",[CoreArchive strForKey:NSDEFAULT_ST_PAYMENT],[CoreArchive boolForKey:NSDEFAULT_ST_PAYMENT_DS ]?@"|代收":@""] componentsSeparatedByString:@"|"];
        payLabel.text = [datas objectAtIndex:[saleOrder.payType intValue]];
    }else
    {
         payLabel.text = @"未付款";
    }
    
    [self tsczClose];
    [orderTableView reloadData];
}

-(void)AAMenuBubbles:(AAMenuBubbles *)shareBubbles andIndex:(int)index
{
    [payLabel setText:payMenu.bubblestrs[index]];
    saleOrder= [AppService getSaleOrderByNo:saleOrder.saleOrderNo];
    saleOrder.isPay = YES;
    saleOrder.paidPrice = saleOrder.totalPrice;
    saleOrder.unpaidPrice = 0;
    saleOrder.payType = [NSString stringWithFormat:@"%d",index];
    // NSArray *paylist=[[CoreArchive strForKey:NSDEFAULT_ST_PAYMENT] componentsSeparatedByString:@"|"];
   // saleOrder.tspayType = [paylist objectAtIndex:index];
    [saleOrder updateToDB];
    [clientTableView reloadData];
     yzfImageView.hidden = NO;
    [self tsczClose];
}

- (void)calendarControllerDidDismissCalendar:(PMCalendarController *)calendarController
{
    saleOrder= [AppService getSaleOrderByNo:saleOrder.saleOrderNo];
    saleOrder.date = [nowDate dateStringWithFormat:YYYYMMDDHHMMSS];
    [saleOrder updateToDB];
    [clientTableView reloadData];
}

#pragma mark --实现系统回掉方法


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if([textField isEqual:clientNameTextView])
    {
        saleOrder= [AppService getSaleOrderByNo:saleOrder.saleOrderNo];
        if(saleOrder.clientId && !isEditClientName)
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否修改固定用户" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"修改", nil];
            alertView.delegate = self;
            [alertView show];
            return NO;
        }
    }
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    saleOrder= [AppService getSaleOrderByNo:saleOrder.saleOrderNo];
    saleOrder.clientId = client.clientId;
    saleOrder.remark = remarkTextField.text;
    saleOrder.date = [nowDate dateStringWithFormat:YYYYMMDDHHMMSS];
    saleOrder.mobile = mobileTextField.text;
    saleOrder.clientName = clientNameTextView.text;
    [saleOrder updateToDB];
    [clientTableView reloadData];
}


#pragma mark --产品大图浏览模式
/*
 *  本地图片展示
 */
-(void)localImageShow:(NSUInteger)index{
    
    __weak typeof(self) weakSelf=self;
    
    //    [PhotoBroswerVC show:self type:PhotoBroswerVCTypeModal index:index photoModelBlock:^NSArray *{
    //
    //        NSArray *localImages = weakSelf.images;
    //
    //        NSMutableArray *modelsM = [NSMutableArray arrayWithCapacity:localImages.count];
    //        for (NSUInteger i = 0; i< localImages.count; i++) {
    //
    //            PhotoModel *pbModel=[[PhotoModel alloc] init];
    //            pbModel.mid = i + 1;
    //            pbModel.image = localImages[i];
    //            [modelsM addObject:pbModel];
    //        }
    //        NSLog(@"size%d",[modelsM count]);
    //        return modelsM;
    //    }];
    [PhotoBroswerVC show:self type:PhotoBroswerVCTypeModal showData:mainProductArray index:index photoModelBlock:^NSArray *{
        NSArray *localImages = weakSelf.images;
        
        NSMutableArray *modelsM = [NSMutableArray arrayWithCapacity:localImages.count];
        for (NSUInteger i = 0; i< localImages.count; i++) {
            
            PhotoModel *pbModel=[[PhotoModel alloc] init];
            pbModel.mid = i + 1;
            pbModel.image = localImages[i];
            [modelsM addObject:pbModel];
        }
        return modelsM;
    }];
}


-(NSArray *)images{
    
    if(_images ==nil){
        NSMutableArray *arrayM = [NSMutableArray array];
        
        //        for (NSUInteger i=0; i<9; i++) {
        //
        //            UIImage *imagae =[UIImage imageNamed:[NSString stringWithFormat:@"%@",@(i+1)]];
        //
        //            [arrayM addObject:imagae];
        //        }
        
        for (int i=0; i<[mainProductArray count]; i++) {
            ProductModel *model = [mainProductArray objectAtIndex:i];
            if([model.photo isValid])
            {
                NSString *imagePath = [ToolUtils getImageLocalPath:model.photo];
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
                [arrayM addObject:image];
            }else
            {
                UIImage *image = [UIImage imageNamed:@"nopic"];
                [arrayM addObject:image];
            }
        }
        
        _images = arrayM;
        NSLog(@"image:%lu",(unsigned long)[_images count]);
    }
    
    return _images;
}


-(void)reloadData:(ChangeType)changeType
{
    [self reloadProductData];
    isEditing = NO;
    bianjiBtn.selected = !bianjiBtn.selected;
}



-(void)handleCategoryLongpressGesture:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        UIButton *button=(UIButton*)gestureRecognizer.view;
        AddCategoryViewController *vc=[[AddCategoryViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        vc.delegate = self;
        vc.category=[categoryArray objectAtIndex:button.tag];
        [self presentViewController:vc animated:YES completion:nil];
    }
}


- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
     SaleOrderInfoModel *model = [productList objectAtIndex:cell.tag];
    NSMutableArray *saleinfoModels = [SaleOrderInfoModel searchWithWhere:[NSString stringWithFormat:@"saleOrderInfoId=%ld",(long)model.saleOrderInfoId] orderBy:nil groupBy:nil offset:0 count:0];
    int number = 0;
    for (SaleOrderInfoModel *m in saleinfoModels) {
        number = number+ m.productNumber;
        [m deleteToDB];
    }
    
    
    ProductModel *productModel = [model product];
    productModel.totalNumber = productModel.totalNumber + number;
    [productModel updateDate];
    
    SaleOrderModel *orderModel = model.saleOrder;
    model.saleOrder.orderPrice = model.saleOrder.orderPrice - model.price * number;
    [orderModel updateToDB];

    [self reloadOrderListData];
}

- (void)gesturePasswordSuccess
{
    if(index==0)
    {
        PutInProductViewController *pipvc=[[PutInProductViewController alloc] init];
        [self.navigationController pushViewController:pipvc animated:YES];
    }else if (index==1)
    {
        AccountListViewController *settingVc = [[AccountListViewController alloc] init];
        BaseSplitViewController  *settingsplitViewController = [[BaseSplitViewController alloc]init];
        [settingsplitViewController setValue:[NSNumber numberWithFloat:SCREEN_WIDTH/2] forKey:@"_masterColumnWidth"];
        //[settingsplitViewController setValue:[NSNumber numberWithFloat:SCREEN_HEIGHT] forKey:@"_masterColumnHeight"];
        [settingsplitViewController setPresentsWithGesture:YES];
        [settingsplitViewController setViewControllers:[NSArray arrayWithObjects:settingVc,nil, nil]];//横向时index:0左边导航展示，index:1为右边显示的view
        settingsplitViewController.view.backgroundColor = RGBCOLOR(88,34,8);
        [settingsplitViewController.view setBackgroundColor:BACKGROUND_COLOR];
        [self.navigationController presentViewController:settingsplitViewController animated:YES completion:nil];
    }else if (index==2)
    {
        TicketListViewController *tlvc=[[TicketListViewController alloc] init];
        BaseNavigationController *nav=[[BaseNavigationController alloc] initWithRootViewController:tlvc];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    }else if (index==3)
    {
        bianjiBtn.selected = !bianjiBtn.selected;
        isEditing  = bianjiBtn.selected;
        [clientTableView reloadData];
        [mCollectionView reloadData];
    }
}


- (void) textFieldDidChange:(UITextField *) TextField
{
    if([TextField.text isValid])
    {
        if(queryParams.count>0)
        {
            NSMutableString *str = [NSMutableString string];
            for (int i=0; i<[queryParams count]; i++) {
                if(i==[queryParams count]-1)
                {
                    [str appendString:[NSString stringWithFormat:@"categoryId=%d",[queryParams[i] integerValue]]];
                }else
                {
                    [str appendString:[NSString stringWithFormat:@"categoryId=%d or ",[queryParams[i] integerValue]]];
                }
            }
            NSLog(@"data===%@",str);
            mainProductArray = [ProductModel searchWithWhere:[NSString stringWithFormat:@"isDel = 0 and (%@) and modelNo like '%@%@%@'",str,@"%",TextField.text,@"%"] orderBy:nil offset:0 count:0];
        }else
        {
            mainProductArray = [ProductModel searchWithWhere:[NSString stringWithFormat:@"isDel = 0 and modelNo like '%@%@%@'",@"%",TextField.text,@"%"] orderBy:nil offset:0 count:0];
        }
        
        [mCollectionView reloadData];
    }else
    {
        [self reloadProductData];
    }
 
}


-(void)tsczClose
{
    saleOrder = [SaleOrderModel searchSingleWithWhere:[NSString stringWithFormat:@"saleOrderId=%ld",saleOrder.saleOrderId] orderBy:nil];
    if(!saleOrder.isPay && saleOrder.paidPrice>0 && [saleOrder.tspayType isValid])
    {
        zfInfoLabel.hidden = NO;
        zfInfoLabel.text = [NSString stringWithFormat:@"%@ 已付:%0.1f 未付: %0.1f",saleOrder.tspayType,saleOrder.paidPrice,saleOrder.unpaidPrice];
    }else if(saleOrder.isPay && [saleOrder.tspayType isValid])
    {
        zfInfoLabel.hidden = NO;
        zfInfoLabel.text = [NSString stringWithFormat:@"%@ 已付:%0.1f 未付: %0.1f",saleOrder.tspayType,saleOrder.paidPrice,saleOrder.unpaidPrice];
    }else
    {
        zfInfoLabel.hidden = YES;
    }
    NSLog(@"关闭啦");
}

@end
